﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using OpenWaves.Reflection;

namespace OpenWaves.Testing
{
    public class CodeAnalysisRuleSet
    {
        private readonly List<ICodeAnalysisRule> rules = new List<ICodeAnalysisRule>();

        public CodeAnalysisRuleSet()
        {
        }

        public CodeAnalysisRuleSet(IEnumerable<ICodeAnalysisRule> rules)
        {
            this.rules.AddRange(rules);
        }

        public List<ICodeAnalysisRule> Rules
        {
            get { return this.rules; }
        }

        public static CodeAnalysisRuleSet CreateDefault()
        {
            var rules =
                typeof(CodeAnalysisRuleSet).Assembly.GetTypes()
                .Where(t => t.Is<ICodeAnalysisRule>() && t != typeof(ICodeAnalysisRule))
                .Select(Activator.CreateInstance).Cast<ICodeAnalysisRule>();

            return new CodeAnalysisRuleSet(rules);
        }

        public void Run(IEnumerable<string> assemblyNames)
        {
            IEnumerable<Assembly> assemblies = assemblyNames.Select(Assembly.Load);
            this.Run(assemblies);
        }

        public void Run(IEnumerable<Assembly> assemblies)
        {
            foreach (var assembly in assemblies)
            {
                foreach (var rule in this.rules)
                {
                    rule.Run(assembly);
                }
            }
        }
    }
}